//
//  DDUserAccount.swift
//  SinaMicroBlog
//
//  Created by dqw on 15/7/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit


class DDUserAccount: NSObject,NSCoding {
    
     // MARK: - 账户的信息（属性）
    var access_token:String?
    var expires_in: NSTimeInterval = 0{
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate:NSDate?
    var uid: String?
    var name:String?
    var avatar_large:String?
    // TODO: 此处暂时将private去掉 重点
    static var aUserAccount: DDUserAccount?
    
    // 类属性：计算性属性，和 静态属性不同的是，后者属于存储型属性。
    class var isUserLogOn:Bool {
        return loadUserAccount() != nil
//        return false
    }
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
     // MARK: - 得到另外的账户信息 并保持
    func getAnotherUserInfoAndSaveUserAccount(finisehed:(error: NSError?)->()) {
        
        DDNetTools.sharedNetTools.getAnotherUserInfo { (result, error) -> () in
            if result == nil || error != nil {
                finisehed(error: error!)
                return
            }else{
                self.name = result!["name"] as? String
                self.avatar_large = result!["avatar_large"] as? String
                self.saveUserAccount()
                finisehed(error: nil)
            }
        }
    }
    
     // MARK: - 保持账户
   private func saveUserAccount(){
    print(DDUserAccount.accountPath)
        NSKeyedArchiver.archiveRootObject(self, toFile: DDUserAccount.accountPath)
    }
    
     // MARK: - 加载账户，程序启动时要判断是否登陆过，该方法会被调用多次。
    class func loadUserAccount()-> DDUserAccount?{
        
        if aUserAccount == nil{
            aUserAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? DDUserAccount
        }
         // FIXME: 时间的比较方法。
        if let date = aUserAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            aUserAccount = nil
        }
        return aUserAccount
    }
    
     // MARK: - 字典转模型方法。
    init(dict:[String:AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
        // TODO: 测试，这个静态对象的赋值先取消。取消是可以的，因为其是程序运行结束才销毁。
//        DDUserAccount.aUserAccount = self
    }
    
 // MARK: - 编码和解码 方法。
    func encodeWithCoder(aCoder: NSCoder){
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    required init?(coder aDecoder: NSCoder){
      access_token = aDecoder.decodeObjectForKey("access_token") as? String
       expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
       expires_in = aDecoder.decodeDoubleForKey("expires_in")
       uid = aDecoder.decodeObjectForKey("uid") as? String
       name = aDecoder.decodeObjectForKey("name") as? String
       avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    override var description:String{
        
        let properties = ["access_token", "expires_in", "uid","expiresDate", "name", "avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
}
